package com.toymate.mqtt.auth;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.toymate.modules.iot.entity.IotProduct;
import com.toymate.modules.iot.service.IotDeviceService;
import com.toymate.modules.iot.service.IotProductService;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.core.server.auth.IMqttServerAuthHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.tio.core.ChannelContext;

/**
 * mqtt 认证
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Configuration(proxyBeanMethods = false)
@Slf4j
public class MqttAuthHandler implements IMqttServerAuthHandler {

    @Autowired
    private IotProductService productService;

    @Autowired
    private IotDeviceService deviceService;

    @Override
    public boolean authenticate(ChannelContext context, String uniqueId, String clientId, String userName, String password) {
        if (clientId.startsWith("esp32")) {
            log.info("服务端认证通过 clientId:{}", clientId);
            return true;
        } else {
            // 设备端认证
            String[] clientArray = clientId.split("&");
            if (clientArray.length != 2 || clientArray[0].equals("") || clientArray[1].equals("")) {
                log.error("设备mqtt客户端Id格式应为：设备编号  & 产品ID & 用户ID");
                return false;
            }
            String deviceNumber = clientArray[0];
            String productId = Convert.toStr(clientArray[1]);
            IotProduct product = productService.getById(productId);
            if (product == null) {
                return false;
            }
            String mqttPassword = product.getMqttPassword();
            if (StrUtil.isEmpty(mqttPassword)) {
                return false;
            }
            // 验证用户名
            if (!userName.equals(product.getMqttAccount())) {
                return false;
            }
            // 验证密码
            if (!password.equals(product.getMqttPassword())) {
                return false;
            }
            // 设备认证后自动添加设备
            return deviceService.insertDeviceAuto(deviceNumber, productId);
        }
    }
}